package com.liao.healthydiet;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.liao.healthydiet.ui.activity.GuideActivity;
import com.liao.healthydiet.ui.activity.MainActivity;

import java.security.PrivilegedAction;

public class SplashActivity extends AppCompatActivity {

    private static final int INTO_GUIDE = 0x001;
    private static final int INTO_MAIN = 0x002;

    private int countDown = 5;

    private SharedPreferences sp;

    private TextView tv_time;

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case INTO_GUIDE:
                    startActivity(new Intent(SplashActivity.this, GuideActivity.class));
                    break;
                case INTO_MAIN:
                    startActivity(new Intent(SplashActivity.this, MainActivity.class));
                    break;
            }
            finish();
            return false;
        }
    });

    private class MyThread extends Thread {
        @Override
        public void run() {
            while (countDown >= 0) {
                try {
                    sleep(1000);
                    if (countDown == 0) {
                        isFirstRun();
                        break;
                    }
                    tv_time.setText(String.valueOf(--countDown));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        init();
        new MyThread().start();
    }

    private void init() {
        sp = getSharedPreferences("config", MODE_PRIVATE);
        tv_time = findViewById(R.id.tv_time);
    }

    private void isFirstRun() {
        boolean isFirstRun = sp.getBoolean("isFirstRun", true);
        if (isFirstRun) {
            sp.edit().putBoolean("isFirstRun", false).apply();
            handler.sendEmptyMessage(INTO_GUIDE);
        } else {
            handler.sendEmptyMessage(INTO_MAIN);
        }
    }
}
